package com.crayon.account.loader;

import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;

import com.crayon.account.dao.DAOAccount;
import com.crayon.account.dao.DataBaseManager;
import com.crayon.util.GDB;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;

import org.apache.commons.lang3.StringUtils;

import java.util.LinkedList;
import java.util.List;

public class LoaderSQLAccountSingle extends AsyncTaskLoader<List<DAOAccount>> {

	String query;
	public LoaderSQLAccountSingle(Context context,String query) {
		super(context);
		this.query=query;
	}

	@Override
	public List<DAOAccount> loadInBackground() {

		DataBaseManager baseManager =DataBaseManager.getHelper(getContext());
		List<DAOAccount> list =new LinkedList<DAOAccount>();
		try {

			Dao<DAOAccount, Integer> daoAccount =baseManager.getDAOAccount();

			QueryBuilder<DAOAccount, Integer> builder = daoAccount.queryBuilder();
			
			Where<DAOAccount, Integer> where = builder.where();
			
			if(!StringUtils.isEmpty(query)){
				String querySet = "%"+StringUtils.trim(getQuery())+"%";
				where.or(
						where.like("summary",querySet)
						,where.like("desciption", querySet)
						);
			}else{
				where.isNotNull("summary");
			}
			GDB.log(getClass(), "sql " + builder.prepareStatementString());
			list = where.query();
		}catch(Exception e ){
			GDB.log(getClass(), "result search err " + e.getMessage());
		}
		GDB.log(getClass(), "result " + (list==null ? 0 : list.size() )+":::");
		return list;
	}

	@Override
	protected void onStartLoading() {
		// TODO Auto-generated method stub
		super.onStartLoading();
		forceLoad();
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}

}


